package com.lagou.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import org.apache.zookeeper.*;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

// 接收客户端请求,打印在控制台
public class NettyServer2 implements Watcher {

    private static final String IP = "127.0.0.1";
    private static final int PORT = 8081;

    private static final String ZOOKEEPER_ADDRESS = "127.0.0.1:2181";

    private static final String NAMESPACE = "dubbo-";

    private static ZooKeeper zooKeeper;


    public static void main(String[] args) throws Exception {

        zooKeeper = new ZooKeeper(ZOOKEEPER_ADDRESS, 5000, new NettyServer2());

//        connectServer();
//        ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
//        scheduledExecutorService.scheduleAtFixedRate(NettyServer2::updateServerTime, 0, 5, TimeUnit.SECONDS);

        ExecutorService executorService = Executors.newFixedThreadPool(2);
        executorService.submit(NettyServer2::connectServer);


    }

    public static void connectServer() {
        //1.创建2个线程池对象
        //bossGroup 负责接收用户连接
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        //workGroup 负责处理用户的io读写操作
        NioEventLoopGroup workGroup = new NioEventLoopGroup();

        //2.创建启动引导类
        ServerBootstrap serverBootstrap = new ServerBootstrap();

        //3.设置启动引导类
        //添加到组中,两个线程池,第一个位置的线程池就负责接收,第二个参数就负责读写
        serverBootstrap.group(bossGroup, workGroup)
                //给我们当前设置一个通道类型
                .channel(NioServerSocketChannel.class)
                //绑定一个初始化监听
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    //事件监听Channel通道
                    @Override
                    protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                        //获取pipeLine
                        ChannelPipeline pipeline = nioSocketChannel.pipeline();
                        //绑定编码
                        pipeline.addFirst(new StringEncoder());
                        pipeline.addLast(new StringDecoder());
                        //绑定我们的业务逻辑
                        pipeline.addLast(new SimpleChannelInboundHandler<String>() {
                            @Override
                            protected void channelRead0(ChannelHandlerContext channelHandlerContext, String msg) throws Exception {
                                //获取入栈信息,打印客户端传递的数据
                                System.out.println("NettyServer2" + msg);
                            }
                        });
                    }
                });

        //4.启动引导类绑定端口
        try {
            ChannelFuture future = serverBootstrap.bind(IP, PORT).sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        //5.关闭通道
//        future.channel().closeFuture().sync();

    }

    @Override
    public void process(WatchedEvent watchedEvent) {
        if (watchedEvent.getState() == Event.KeeperState.SyncConnected) {

            //解除主程序在CountDownLatch上的等待阻塞
            System.out.println("process方法执行了...");
            // 创建节点
            try {
                createNoteSync();
            } catch (KeeperException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
    }

    private void createNoteSync() throws KeeperException, InterruptedException {

        // 创建节点
        String path = "/" + NAMESPACE + IP + ":" + PORT;
        String content = String.valueOf(System.currentTimeMillis());

        zooKeeper.create(path, content.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
    }

    /**
     * 更新服务端的时间
     */
    public static void updateServerTime() {
        String path = "/" + NAMESPACE + IP + ":" + PORT;
        System.out.println("定时任务开始执行：" + System.currentTimeMillis());
        String noteData = null;
        try {
            noteData = getNoteData(path);
            if (System.currentTimeMillis() - Long.parseLong(noteData) > 5000) {
                setNoteData(path, String.valueOf(System.currentTimeMillis()));
            }
        } catch (KeeperException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /*
  获取某个节点的内容
*/
    private static String getNoteData(String nodeName) throws KeeperException, InterruptedException {

        /**
         * path    : 获取数据的路径
         * watch    : 是否开启监听
         * stat    : 节点状态信息
         *        null: 表示获取最新版本的数据
         *  zk.getData(path, watch, stat);
         */
        byte[] data = zooKeeper.getData("/" + nodeName, false, null);
//        System.out.println("data:" + new String(data));
        return new String(data);

    }

    private static void setNoteData(String nodeName, String data) throws KeeperException, InterruptedException {
        zooKeeper.setData("/" + nodeName, data.getBytes(), -1);

    }
}
